package cn.cvs.service.impl;

import cn.cvs.dao.SysUserMapper;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;


@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    SysUserMapper sysUserMapper;
    @Override
    public SysUser queryUser(String account, String password) {
//        if(1==1){
//             throw  new RuntimeException("故意制造的异常");
//        }
        SysUser sysUser = sysUserMapper.queryOne(account, password);
        return sysUser;
    }

    @Override
    public List<SysUser> queryUsers(String realName, Integer roleId, Integer pageNo, Integer pageSize) {
        List<SysUser> sysUsers = sysUserMapper.queryByPage(realName, roleId, (pageNo - 1) * pageSize, pageSize);
        return sysUsers;
    }

    @Override
    public int queryCount(String realName, Integer roleId) {
        int count = sysUserMapper.queryCount(realName, roleId);
        return count;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int addUser(SysUser sysUser) {
        int add = sysUserMapper.add(sysUser);
        return add;
    }

    @Override
    public SysUser queryById(Integer id) {
        SysUser sysUser = sysUserMapper.queryById(id);
        return sysUser;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int updateUser(SysUser sysUser) {
        int update = sysUserMapper.update(sysUser);
        return update;
    }

    @Override
    public int queryUserCount(String account) {
        int i = sysUserMapper.queryUserCount(account);
        return i;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int deleteUser(Integer id, HttpServletRequest request) {
          //删除图片
        SysUser sysUser = sysUserMapper.queryById(id);
        if(!StringUtils.isEmpty(sysUser.getIdPicPath())){
            //删除身份照
            String idPicPath = request.getSession()
                    .getServletContext().getRealPath(sysUser.getIdPicPath());
            File idPic = new File(idPicPath);
            if(idPic.exists()){
                idPic.delete();
            }
        }
            if(!StringUtils.isEmpty(sysUser.getWorkPicPath())){
                  //删除工作照
                String workPicPath = request.getSession()
                        .getServletContext().getRealPath(sysUser.getWorkPicPath());
                File workPic = new File(workPicPath);
                if(workPic.exists()){
                      workPic.delete();
                }
            }
        //删除数据库中的记录
        int i = sysUserMapper.deleteById(id);
        return i;
    }
}
